
const app = getApp()
const api = app.globalData.api

Page({

  /**
   * 页面的初始数据
   */
  data: {
    childId:'',//当前编辑的明细ID
    classify:'',//报销类型
    search_type:'',//当前是哪个选项
    typeOption:[],
    time_popup_show:false,
    type_popup_show:false,
    children:[
      {
        id: Math.random().toString(36).substring(2),
        type:'',
        applyDate:'',
        money:'',
        text:'',
        unit:app.unit,
        attachFile:[],
      }
    ]
  },
  /**添加报销明细 */
  addChild(){
    let id = Math.random().toString(36).substring(2);
    let child={
      id:id,
      type:'',
      applyDate:'',
      money:'',
      text:'',
      unit:app.unit,
      attachFile:[]
    }
    let arr = this.data.children
    arr.push(child);
    this.setData({
      children:arr
    })
  },
  /**删除元素 */
  delChild(e){
    let id = e.currentTarget.dataset.id;
    let arr = this.data.children
    let newArr = arr.filter(item => item.id !=id );
    this.setData({
      children:newArr
    })
  },
 /**报销类型 */
 showTypePopup(e) {
  let that = this;
  let type = e.currentTarget.dataset.type;
  let id = e.currentTarget.dataset.id;
  if(type=='classify'){
    api.curlPost('?cla=costApp&fun=search').then((res)=>{
      that.setData({
        childId:id,
        search_type:'classify',
        type_popup_show:true,
        typeOption:res.data.result.typeOption
      })
    })
  }else if(type =='feeType'){
    api.curlPost('?cla=costApp&fun=search').then((res)=>{
      that.setData({
        childId:id,
        search_type:'feeType',
        type_popup_show:true,
        typeOption:res.data.result.feeTypeOption
      })
    })
  }
  
},
 /**报销类型弹出层关闭 */
 onTypeCancel(e){
  this.setData({
    type_popup_show:false
  })
},
/**报销类型确认 */
onTypeConfirm(event){
  const { picker, value, index } = event.detail;
  if(this.data.search_type =='classify'){
    this.setData({
      classify:`${value}`,
      type_popup_show:false
    })
  }else if(this.data.search_type=='feeType'){
    let children = this.reChildren(this.data.childId,value,'type');
    this.setData({
      children:children,
      type_popup_show:false
    })
  }
},
/**选择时间 */
  chooseTime(e){
    let id = e.currentTarget.dataset.id;
    let time = this.byIdGetList(id,'applyDate');
    let currentTimestamp = '';
    currentTimestamp = time?new Date(time).getTime():new Date().getTime();
    this.setData({
      childId:id,
      time_popup_show:true,
      currentTimestamp:currentTimestamp
    })
  },
  /**日期选择确认 */
  timeConfirm(event){
    let date = new Date(event.detail);
    this.setData({
      children:this.reChildren(this.data.childId,api.formatDateCRM('Y-m-d',date),'applyDate'),
      time_popup_show:false
    })
   
  },
  timeCancel(e){
    this.setData({
      time_popup_show:false
    })
  },
  commit(e){
   
    let para = e.detail.value;
    para.id = api.isBlank(this.data.info.id)?'':this.data.info.id;
    para.children = JSON.stringify(this.data.children);
    
    api.curlPost('?cla=costApp&fun=commitEdit',para).then((res)=>{
        wx.redirectTo({
          url: '../costInfo/costInfo?id='+res.data.id,
        })
    })
   
  },
  /**明细内容改变时修改 */
  changeMx(e){
    let field = e.currentTarget.dataset.field;
    let id = e.currentTarget.dataset.id;
    this.setData({
      children:this.reChildren(id,e.detail,field)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let id = api.isBlank(options.id)?'':options.id;
    api.curlPost('?cla=costApp&fun=editPage',{id:id}).then((res)=>{
      that.setData({
        info:res.data.result.info,
        classify:res.data.result.info.type,
        children:api.isBlank(res.data.result.list)?that.data.children:res.data.result.list
      })
    })
  },

  /**上传文件 */
  afterRead(event) {
    let id = event.currentTarget.dataset.id;
    let that = this;
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式

    api.uploadFileCRM(app.root+'?cla=fileUploadApp&fun=uploadFile',file,{power: 'payment',fileType:'费用报销'}).then((res)=>{
      // 上传完成需要更新 fileList
           let fileList= that.byIdGetList(id,'file');
           fileList.push({ ...file, url: res.result.src,id:res.result.id });
           that.setData({
            children: that.reChildren(id,fileList,'file')
          })
         })
  },

  /**根据明细ID获取此明细数组 */
  byIdGetList(id,field){
    let children = this.data.children;
    if(field =='file'){
      let fileList = [];
      children.forEach((v,i)=>{
        if(v.id==id){
          fileList = v.attachFile
        }
      });
      return fileList;
    }else{
      children.forEach((v,i)=>{
        if(v.id==id){
          let val = '';
          switch(field){
            case 'type':
             val =  v.type;
             break;
             case 'applyDate':
             val =  v.applyDate;
             break;
          }
          return val;
        }
      });

    }
   
   
  },
  
  /**重新组装明细数组 */
  reChildren(id,value,field){
    let children = this.data.children;
    let newChildren=[];
    children.forEach((v,i)=>{
      if(v.id==id){
        switch(field){
          case 'type':
            v.type=value;
            newChildren.push(v);
            break;
            case 'money':
              v.money=value;
              newChildren.push(v);
              break;
              case 'applyDate':
                v.applyDate=value;
                newChildren.push(v);
                break;
                case 'text':
                  v.text=value;
                  newChildren.push(v);
                  break;
                  case 'file':
                    v.attachFile=value;
                    newChildren.push(v);
                    break;
        }
      }else{
        newChildren.push(v);
      }
    })
    return newChildren;
  },


 /**删除文件 */
 delFile(event){
  let index = event.detail.index;
  console.log(event)
  let childId = event.currentTarget.dataset.id;
  let fileList = this.byIdGetList(childId,'file');
  let newFileList=[];
  let id = '';
  fileList.forEach((v,i)=>{
    if(i==index){
      id=v.id;
    }else{
      newFileList.push(v);
    }
  })

  let that = this;
  api.curlPost('?cla=fileUploadApp&fun=delFile',{id:id,power:'workReportDay'}).then((res)=>{
    that.setData({
      children:that.reChildren(childId,newFileList,'file')
    })
  })
  
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})